package com.sinoyd.itszyw.Fragment;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import com.sinoyd.itszyw.Adapter.RoutineInspectionAdapter;
import com.sinoyd.itszyw.Dialog.LoadingDialog;
import com.sinoyd.itszyw.Model.RoutineInspectionInfo;
import com.sinoyd.itszyw.R;
import com.sinoyd.itszyw.Util.DateUtils;
import com.sinoyd.itszyw.View.WaterDropListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.ex.DbException;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.sinoyd.itszyw.MyApplication.GetInspection;
import static com.sinoyd.itszyw.MyApplication.db;
import static com.sinoyd.itszyw.MyApplication.loginId;
import static com.sinoyd.itszyw.MyApplication.postRoutineInspection;

/**
 * @author: Sinoyd  --------->作者
 * @description: --------->描述
 * @projectName: ITSZYW  ---------> 项目名称
 * @date: 2017-03-09 ---------> 创建日期
 * @time: 16:06       ---------> 创建时间
 */
@ContentView(R.layout.fragment_routine_inspection)
public class RoutineInspectionFragment extends BaseFragment implements WaterDropListView.IWaterDropListViewListener {

    @ViewInject(R.id.txt_title)
    private TextView txt_title;
    @ViewInject(R.id.inspection_calender)
    private TextView inspection_calender;

    private String endTimeStr = "";
    private Calendar calendar;

    private static int GET_INSPECTION = 111;

    private static int POST_INSPECTION = 222;
    private int REFRESH_FLAG = 0;
    private RoutineInspectionAdapter mAdapter;
    @ViewInject(R.id.waterdrop_listview)
    private WaterDropListView mListView;
    private List<RoutineInspectionInfo> list = new ArrayList();
    private LoadingDialog loadingDialog;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        txt_title.setText(this.getResources().getString(R.string.inspection_routine));
        try {
            list = db.findAll(RoutineInspectionInfo.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
        initView();
    }


    private void initView() {

        loadingDialog = new LoadingDialog(getActivity(), R.style.dialog_translucent_notitle);
        calendar = Calendar.getInstance();

        Date dateNow = new Date();
        inspection_calender.setText(String.format("%tF", dateNow));
        mAdapter = new RoutineInspectionAdapter(getActivity(), list);
        mListView.setAdapter(mAdapter);
        mListView.setWaterDropListViewListener(this);
        mListView.setPullLoadEnable(true);


    }

    private void getData() {
        RequestParams params = new RequestParams(GetInspection);
        params.addQueryStringParameter("validation", "sinoyd123!@#");
        try {
            sendHttpRequest(params, HttpMethod.GET, GET_INSPECTION);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void httpOnSuccess(String responseStr, int requestCode) {

        if (requestCode == GET_INSPECTION) {
            try {
                list = new ArrayList();
                JSONObject object = new JSONObject(responseStr);
                if (object.getBoolean("IsSuccess")) {
                    JSONArray array = object.getJSONArray("Data");
                    for (int i = 0; i < array.length(); i++) {
                        RoutineInspectionInfo inspectionInfo = new RoutineInspectionInfo();
                        try {
                            inspectionInfo.ParseRoutineInspectionInfo(array.getJSONObject(i));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        list.add(inspectionInfo);


                    }
                    initView();
                    try {
                        db.dropTable(RoutineInspectionInfo.class);
                        db.save(list);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    if (REFRESH_FLAG == 1) {
                        mListView.stopRefresh();
                        showToast("刷新成功");

                    }

                } else {

                    showToast("获取巡检项数据失败!");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (requestCode == POST_INSPECTION) {

            try {
                loadingDialog.show();
                JSONObject object = new JSONObject(responseStr);
                if (object.getBoolean("IsSuccess")) {

                    showToast("上传成功~");
                } else {
                    showToast(object.getString("上传失败!!!"));
                }
                loadingDialog.dismiss();
            } catch (JSONException e) {
                e.printStackTrace();
                showToast(e.getMessage());
            }

        }

    }


    @Event({R.id.uploading, R.id.linear_date})
    private void getOnClick(View view) {
        switch (view.getId()) {
            case R.id.linear_date:

//                final  DatePickerDialog datePickerDialog = new DatePickerDialog(this.getActivity(), new DatePickerDialog.OnDateSetListener() {
//
//                    @Override
//                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//                        endTimeStr = String.format("%d-%02d-%d", year, monthOfYear + 1, dayOfMonth);
//
//
//                        SimpleDateFormat format = new SimpleDateFormat(
//                                "yyyy-MM-dd");
//                        Date dateEnd = null;
//                        try {
//                            dateEnd = format.parse(endTimeStr);// 完成日期
//                        } catch (ParseException e) {
//                            e.printStackTrace();
//                        }
//                        inspection_calender.setText(String.format("%tF", dateEnd));
//                        calendar.setTime(dateEnd);// 设置结束日历时间
//                    }
//                }, calendar.get(calendar.YEAR), calendar.get(calendar.MONTH), calendar.get(calendar.DAY_OF_MONTH));
//
                final DatePickerDialog datePickerDialog = new DatePickerDialog(this.getActivity(), null, calendar.get(calendar.YEAR), calendar.get(calendar.MONTH), calendar.get(calendar.DAY_OF_MONTH));

                //手动设置按钮
                datePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, "完成", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //通过mDialog.getDatePicker()获得dialog上的DatePicker组件，然后可以获取日期信息
                        DatePicker datePicker = datePickerDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        endTimeStr = String.format("%d-%02d-%02d", year, month + 1, day);


                        SimpleDateFormat format = new SimpleDateFormat(
                                "yyyy-MM-dd");
                        Date dateEnd = null;
                        try {
                            dateEnd = format.parse(endTimeStr);// 完成日期
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        inspection_calender.setText(String.format("%tF", dateEnd));
                        calendar.setTime(dateEnd);// 设置结束日历时间
                    }
                });
                //取消按钮，如果不需要直接不设置即可
                datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("BUTTON_NEGATIVE~~");
                    }
                });

                datePickerDialog.getDatePicker().setMaxDate(new Date().getTime());
                datePickerDialog.show();

                break;
            case R.id.uploading:


                if (inspection_calender.getText().equals("")) {
                    showToast("请先选择日期");
                    break;
                }
                RequestParams params = new RequestParams(postRoutineInspection);
                JSONArray jsonArray = new JSONArray();
                for (int i = 0; i < list.size(); i++) {
                    JSONObject jsonObject = new JSONObject();
                    RoutineInspectionInfo inspectionInfo = (RoutineInspectionInfo) list.get(i);

                    try {
                        jsonObject.put("Content", inspectionInfo.title);
                        jsonObject.put("IsNormal", inspectionInfo.stateId);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    jsonArray.put(jsonObject);

                }

                Date dateNow = new Date();

                String uploadDate = DateUtils.getDateStrNumber(inspection_calender.getText().toString() + String.format("%tT", dateNow));
                params.addBodyParameter("ProcessTime", uploadDate);
                params.addBodyParameter("ProcessMan", loginId);
                params.addBodyParameter("jsontxt", jsonArray.toString());
                params.addBodyParameter("validation", "sinoyd123!@#");

                try {
                    sendHttpRequest(params, HttpMethod.POST, POST_INSPECTION);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
        }

    }


    @Override
    public void onRefresh() {
        REFRESH_FLAG = 1;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                getData();

            }
        }, 500);
    }

    @Override
    public void onLoadMore() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                try {
//                    list.add(db.findFirst(RoutineInspectionInfo.class));
//                } catch (DbException e) {
//                    e.printStackTrace();
//                }
                showToast("暂无更多数据");
                mAdapter.notifyDataSetChanged();
                mListView.stopLoadMore();
            }
        }, 500);

    }


}